/**
 * Copyright 2007-2008 Alex Tkachman
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ait.actors;

import java.util.concurrent.locks.ReentrantLock;

public class LockableDeque<V> extends ReentrantLock implements StealableDeque<V> {
    private V [] data;
    private int startIndex, size;

    public LockableDeque() {
        data = (V[]) new Object[16];
        startIndex = 4;
        size = 0;
    }

    private int normalize(int i) {
        final int len = data.length;
        for (;;) {
            if (i < 0)
              i += len;
            else
              if (i >= len)
                i -= len;
              else
                return i;
        }
    }

    private void resize() {
        Object [] newData = new Object[2*size];
        int sz = size/2;
        for (int i = 0; i != size; ++i) {
            newData [sz+i] = data[normalize(startIndex+i)];
        }
        startIndex = sz;
        data = (V[]) newData;
    }

    public void addFirst(V value) {
        lock();
        try {
            if (size == data.length) {
                resize ();
            }
            startIndex = normalize(startIndex-1);
            size++;
            data [startIndex] = value;
        }
        finally {
           unlock();
        }
    }

    public void addLast(V run) {
        lock();
        try {
            if (size == data.length) {
                resize ();
            }
            data [normalize(startIndex+size)] = run;
            size++;
        }
        finally {
           unlock();
        }
    }

    public V removeFirst() {
        lock();

        try {
           if (size == 0)
             return null;

           V res = data [startIndex];
           data [startIndex] = null;
           size--;
           if (size != 0)
               startIndex = normalize(startIndex+1);
           return res;
        }
        finally {
            unlock();
        }
    }

    public V removeLast() {
        lock();
        try {
            if (size == 0)
              return null;

            int resIndex = normalize(startIndex+size-1);
            V res = data [resIndex];
            data [resIndex] = null;
            size--;
            return res;
        }
        finally {
            unlock();
        }
    }

    public int getSize() {
        return size;
    }
}
